package com.itheima.sfbx.insurance.service.impl;

import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.insurance.pojo.Coefficent;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.CoefficentVO;
import com.itheima.sfbx.insurance.enums.CoefficentEnum;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.CoefficentMapper;
import com.itheima.sfbx.insurance.pojo.CategoryCoefficent;
import com.itheima.sfbx.insurance.pojo.Coefficent;
import com.itheima.sfbx.insurance.pojo.InsuranceCoefficent;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICoefficentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.insurance.service.IInsuranceCoefficentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.sfbx.insurance.constant.CoefficentCacheConstant;
import com.itheima.sfbx.insurance.dto.CoefficentVO;
import com.itheima.sfbx.insurance.enums.CoefficentEnum;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.google.common.collect.Lists;
import java.util.ArrayList;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description：系数项服务实现类
 */
public class CoefficentServiceImpl extends ServiceImpl<CoefficentMapper, Coefficent> implements ICoefficentService {



    @Override
    public Page<CoefficentVO> findPage(CoefficentVO coefficentVO, int pageNum, int pageSize) {
        //分页查询系数项
        LambdaQueryWrapper<Coefficent> lambdaQueryWrapper = getQueryWrapper(coefficentVO);
        Page<Coefficent> page = page(new Page<>(pageNum, pageSize), lambdaQueryWrapper);
        // 转为对应vo返回
        return BeanConv.toPage(page, CoefficentVO.class);
    }

    private LambdaQueryWrapper<Coefficent> getQueryWrapper(CoefficentVO coefficentVO) {
        LambdaQueryWrapper<Coefficent> safeguardLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Coefficent> lambdaQueryWrapper = safeguardLambdaQueryWrapper
                .eq(StringUtils.isNotBlank(coefficentVO.getCoefficentKey()), Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .like(StringUtils.isNotBlank(coefficentVO.getCoefficentKeyName()), Coefficent::getCoefficentKeyName, coefficentVO.getCoefficentKeyName())
                .eq(StringUtils.isNotBlank(coefficentVO.getDataState()), Coefficent::getDataState, coefficentVO.getDataState());
        return lambdaQueryWrapper;
    }

    @Override
    public CoefficentVO findById(String coefficentId) {
        //TODO
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CoefficentVO save(CoefficentVO coefficentVO) {
        //TODO
        //1.校验参数
        if (ObjectUtil.isNull(coefficentVO)) {
            log.error("参数异常");
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }
        // 2.判断key是否重复
        Integer count = lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .count();
        if (count > 0) {
            log.error("新增系数项失败，系数项key已存在 ：{}"+ coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }
        // 3.新增系数项
        Coefficent coefficent = BeanConv.toBean(coefficentVO, Coefficent.class);
        save(coefficent);
        return BeanConv.toBean(coefficent, CoefficentVO.class);
    }

    @Autowired
    private ICategoryCoefficentService categoryCoefficentService;
    @Autowired
    private IInsuranceCoefficentService insuranceCoefficentService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(CoefficentVO coefficentVO) {
        //TODO
        // 1.校验参数
        if (ObjectUtil.isNull(coefficentVO)) {
            log.error("修改系数项失败，参数异常");
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        // 2.校验系数项是否存在
        Coefficent coefficent = lambdaQuery()
                .eq(Coefficent::getId, coefficentVO.getId())
                .one();
        if (ObjectUtil.isNull(coefficent)) {
            log.error("修改系数项失败，系数项信息不存在：{}" + coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        // 3.判断key是否重复
        Integer count = lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .ne(Coefficent::getId, coefficentVO.getId())
                .count();
        if (count > 0) {
            log.error("修改系数项失败，系数项key已存在：{}" + coefficent.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        // 4.校验当前系数项是否存在关联关系
        boolean result = checkRelationship(coefficent);
        if (result) {
            log.error("修改系数项失败，当前系数项存在关联关系：{}" + coefficent.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        // 5.校验完成 更新系数项
        return updateById(BeanConv.toBean(coefficentVO, Coefficent.class));
    }

    private boolean checkRelationship(Coefficent coefficent) {
        Integer countForCategory = categoryCoefficentService.lambdaQuery()
                .eq(CategoryCoefficent::getCoefficentKey, coefficent.getCoefficentKey())
                .count();
        Integer countForInsurance = insuranceCoefficentService.lambdaQuery()
                .eq(InsuranceCoefficent::getCoefficentKey, coefficent.getCoefficentKey())
                .count();
        if (countForCategory > 0 || countForInsurance > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //TODO
        //1.校验参数
        if (ObjectUtil.isEmpty(checkedIds)) {
            log.error("删除系数项失败，参数异常：{}" + checkedIds);
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
        List<Long> ids = BeanConv.toBeanList(Arrays.asList(checkedIds), Long.class);
        // 2.校验保障项是否存在
        List<Coefficent> coefficentList = lambdaQuery()
                .in(Coefficent::getId, ids)
                .list();
        if (coefficentList.size() != checkedIds.length) {
            log.error("删除系数项失败，参数异常：{}" + ids);
            throw new ProjectException(CoefficentEnum.DEL_FAIL);
        }
        // 3.查询保障项是否存在关联
        for (Coefficent coefficent : coefficentList) {
            if (checkRelationship(coefficent)) {
                log.error("删除系数项失败，当前保障项存在关联 :{}" + coefficent.getCoefficentKey());
                throw new ProjectException(SafeguardEnum.DEL_FAIL);
            }
        }
        // 3.不存在关联关系 批量删除保障项
        return removeByIds(ids);
    }

    @Override
    public List<CoefficentVO> findList(CoefficentVO coefficentVO) {
        //TODO
        LambdaQueryWrapper<Coefficent> lambdaQueryWrapper = getQueryWrapper(coefficentVO);
        List<Coefficent> coefficentList = list(lambdaQueryWrapper);
        return BeanConv.toBeanList(coefficentList, CoefficentVO.class);
    }

    @Override
    public CoefficentVO findByCoefficentKey(String coefficentKey) {
        //TODO
        // 1.校验参数
        if (StringUtils.isBlank(coefficentKey)) {
            log.error("查询保障项对象失败，参数异常：{}" + coefficentKey);
            throw new ProjectException(CoefficentEnum.FIND_ONE_FAIL);
        }
        // 2.查询保障项信息
        Coefficent coefficent = lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentKey)
                .one();
        if (ObjectUtil.isNull(coefficent)) {
            log.error("查询保障项对象失败，保障项不存在：{}" + coefficentKey);
            throw new ProjectException(CoefficentEnum.FIND_ONE_FAIL);
        }
        return BeanConv.toBean(coefficent, CoefficentVO.class);
    }
}